﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using GTAuto.DAL.DAL;
using GTAuto.DAL.Entities;


namespace GTAuto.TestApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string HttpPost(string uri, string parameters)
        {
            // parameters: name1=value1&name2=value2	
            WebRequest webRequest = WebRequest.Create(uri);
            //string ProxyString = 
            //   System.Configuration.ConfigurationManager.AppSettings
            //   [GetConfigKey("proxy")];
            //webRequest.Proxy = new WebProxy (ProxyString, true);
            //Commenting out above required change to App.Config
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(parameters);
            Stream os = null;
            try
            {
                // send the Post
                webRequest.ContentLength = bytes.Length; //Count bytes to send
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length); //Send it
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "HttpPost: Request error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            try
            {
                // get the response
                WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                {
                    return null;
                }
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                return sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message, "HttpPost: Response error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return null;
        }

        // end HttpPost 

        private void button1_Click(object sender, EventArgs e)
        {

            //var req = string.Format("http://gis-lab.info/data/mp/kladr/");
            //string httpPost = HttpPost(req, "");
            //using (StringReader reader = new StringReader(httpPost))
            //{
            //    string line;
            //    while ((line = reader.ReadLine()) != null)
            //    {
            //        if (line == "<tr><th colspan=8>Регионы</tr>") break;
            //    }
            //    while ((line = reader.ReadLine()) != "</table>")
            //    {
            //        string[] splts = new string[5];

            //        splts[0] = "<tr><td><a href='?code=";
            //        splts[1] = "'>";
            //        splts[2] = "</a><td>";
            //        splts[3] = "<td width='5%'>&nbsp;<td>";
            //        splts[4] = "</tr>";



            //        string[] strings = line.Split(splts, StringSplitOptions.RemoveEmptyEntries);

            //        GTRegion region = new GTRegion();
            //        region.Id = Convert.ToInt32(strings[0].Substring(0, 2).TrimStart('0'));
            //        region.KladrCode = strings[0];
            //        region.Name = strings[1];
            //        region.Type = strings[2];
            //        DALKladr.Singleton.RegionAdd(region);
            //    }


            //}

            foreach (var gtRegion in DALKladr.Singleton.RegionsGetPaged())
            {

                MessageBox.Show(gtRegion.Name);

                var req = string.Format("http://gis-lab.info/data/mp/kladr/?code={0}", gtRegion.KladrCode);

                string httpPost = HttpPost(req, "");


                using (StringReader reader = new StringReader(httpPost))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line == "<tr><th colspan=8>Города</tr>") break;
                    }


                    while ((line = reader.ReadLine()) != "</table>")
                    {

                        if (line == "</table>" || line == "<tr><th colspan=8>Посёлки</tr>" || line == null || line == "<tr><th colspan=8>Упразднены</tr>")
                            break;

                        string[] splts = new string[5];

                        splts[0] = "<tr><td><a href='?code=";
                        splts[1] = "'>";
                        splts[2] = "</a><td>";
                        splts[3] = "<td width='5%'>&nbsp;<td>";
                        splts[4] = "</tr>";



                        string[] strings = line.Split(splts, StringSplitOptions.RemoveEmptyEntries);

                        //GTRegion region = new GTRegion();
                        //region.Id = Convert.ToInt32(strings[0].Substring(0, 2).TrimStart('0'));
                        //region.KladrCode = strings[0];
                        //region.Name = strings[1];
                        //region.Type = strings[2];
                        //DALKladr.Singleton.RegionAdd(region);

                        GTCity city = new GTCity();
                        city.RregionId = gtRegion.Id;
                        // city.Id = Convert.ToInt32(strings[5]);
                        city.Name = strings[1];
                        city.KladrCode = strings[0];

                        DALKladr.Singleton.CityAdd(city);
                    }

                }
            }

            MessageBox.Show("22");

        }
    }
}
